function success = hdr_SaveVoxelData(hfile, flip)
% HDR::SaveVoxelData  - save Analyze image voxel data
%
% FORMAT:       hdr.SaveVoxelData([flip]);
%
% Input fields:
%
%       flip        optional flipping string (e.g. 'xy', default: '')
%
% No output fields.

% Version:  v0.7f
% Build:    8110521
% Date:     Nov-05 2008, 9:00 PM CET
% Author:   Jochen Weber, SCAN Unit, Columbia University, NYC, NY, USA
% URL/Info: http://wiki.brainvoyager.com/BVQXtools

% argument check
if nargin < 1 || ...
    numel(hfile) ~= 1 || ...
   ~isBVQXfile(hfile, 'hdr')
    error( ...
        'BVQXfile:BadArgument', ...
        'Invalid call to %s.', ...
        mfilename ...
    );
end
if nargin < 2 || ...
   ~ischar(flip) || ...
    numel(flip) > 3
    flip = '';
else
    flip = lower(flip(:)');
end
if any(flip == 'x')
    xflip = true;
else
    xflip = false;
end
if any(flip == 'y')
    yflip = true;
else
    yflip = false;
end
if any(flip == 'z')
    zflip = true;
else
    zflip = false;
end

% get HDR file name -> IMG file
hdrs = bvqxfile_getscont(hfile.L);
hdrc = hdrs.C;
fflp = hdrs.F;

% look in same folder
[ffpn, fflp] = fileparts(fflp);
ifname = [ffpn filesep fflp '.img'];
ifnamc = [ffpn filesep fflp '.IMG'];
if ~exist(ifname, 'file') == 2 && ...
    exist(ifnamc, 'file') == 2
    ifname = ifnamc;
end

% get data size and type
try
    dsize = hdrc.ImgDim.Dim(2:1 + hdrc.ImgDim.Dim(1));
    tsize = prod(dsize);
catch
    error( ...
        'BVQXfile:BadFileContent', ...
        'Analyze ImgDim.Dim field error.' ...
    );
end
dtype = hdrc.ImgDim.DataType;
if isempty(dtype)
    dtype = 0;
end
endian = hdrs.S.EncodingSyntax;
if dtype > 255
    dtype = fix(dtype / 256);
    switch lower(endian)
        case {'ieee-le'}
            endian = 'ieee-be';
        case {'ieee-be'}
            endian = 'ieee-le';
        otherwise
            error( ...
                'BVQXfile:InternalError', ...
                'Bad machine datatype/encoding syntax combination.' ...
            );
    end
end
[tmat, stype] = analyzetype(dtype);
stype = splittocell(stype, '=');
stype = stype{1};

% occupy mem
try
    if ~any([xflip, yflip, zflip])
        tmat = reshape(hdrc.VoxelData(:), [tsize, 1]);
    else
        tmat = hdrc.VoxelData;
        if istransio(tmat)
            tmat = resolve(tmat);
        end
        if xflip
            tmat = tmat(end:-1:1, :, :, :);
        end
        if yflip
            tmat = tmat(:, end:-1:1, :, :);
        end
        if zflip
            tmat = tmat(:, :, end:-1:1, :);
        end
        tmat = reshape(tmat, [tsize, 1]);
    end
catch
    error( ...
        'BVQXfile:InvalidArraySize', ...
        'Invalid VoxelData array size.' ...
    );
end

% open image file
try
    fid = [];
    fid = fopen(ifname, 'wb', endian);
    fseek(fid, 0, 'bof');
    if hdrc.ImgDim.VoxOffset > 0
        fwrite(fid, ...
            char(zeros(1, floor(hdrc.ImgDim.VoxOffset))), ...
            'char');
    end
catch
    try
        fclose(fid);
    catch
        % nothing
    end
    error( ...
        'BVQXfile:FileNotReadable', ...
        'Error opening/writing image file %s.', ...
        ifname ...
    );
end

% write data to voxeldata file
try
    success = (fwrite(fid, tmat, stype) == tsize);
catch
    success = false;
    warning( ...
        'BVQXfile:ErrorWritingData', ...
        'Couldn''t write image data into file %s.', ...
        ifname ...
    );
end
fclose(fid);
